/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import picounit.features.Feature;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;

class FeatureCodeVisitor implements CodeVisitor {
	private final FileReader fileReader = new FileReader();
	private final Prefixer prefixer = new Prefixer();

	private final FeatureRegistry featureRegistry;
	private final Set<String> featuresLoaded;
	private final FeatureInstantiator featureInstantiator;

	public FeatureCodeVisitor(FeatureRegistry featureRegistry, Set<String> featuresLoaded,
		FeatureInstantiator featureInstantiator) {

		this.featureRegistry = featureRegistry;
		this.featuresLoaded = featuresLoaded;
		this.featureInstantiator = featureInstantiator;
	}

	public Status visit(Code code) {
		// System.out.println("Inserting features for: " + code);
		try {
			for (String line : fileReader.readLines(code.openFile(Feature.FILE_NAME))) {
				if (!line.startsWith("#")) {
					new ParsedFeatureDescription(line, prefixer, featureInstantiator)
						.insertInto(featureRegistry, featuresLoaded);
				}
			}
			
			return Status.Success;
		}
		catch (FileNotFoundException fileNotFoundException) {
		}
		catch (IOException ioException) {
		}

		return Status.Failure;
	}
}
